import React, { Component } from 'react';
import { Input, message } from 'antd';
import CustomForm from '../../../components/CustomForm';
import services from '../../../services/api';

class TagAdd extends Component {
  constructor(props) {
    super(props);
    this.state = {
      depts: [],
      hasRight: [],
    };
    this.form = null;
    this.api = 'tag';
  }

  handleSubmit = () => {
    const { actionType, closeModal, value = {} } = this.props;
    this.form.validateFields((err, values) => {
      if (!err) {
        const { name, code, remark } = values;
        const params = {
          name,
          code,
          remark,
          id: value.id,
        };
        services[this.api][actionType](params).then((data) => {
          if (data.code === '0') {
            message.success(data.msg);
            closeModal && closeModal();
          } else {
            message.error(data.msg);
          }
        });
      }
    });
  };

  render() {
    const { actionType, value = {} } = this.props;
    const { name, code, remark } = value;
    const formItems = [
      {
        label: {
          label: '标签名称',
        },
        name: 'name',
        options: {
          initialValue: name,
          rules: [{ required: true, message: '请输入标签名称' }],
        },
        component: <Input placeholder='请输入' disabled={actionType === 'detail'} />,
      },
      {
        label: {
          label: '标签code',
        },
        name: 'code',
        options: {
          initialValue: code,
          rules: [
            { required: true, message: '请输入标签code' },
            { max: 128, message: '最长128个字符' },
            { pattern: /^[a-zA-Z][_a-zA-Z0-9]*$/, message: '限英文数字下划线，并以英文开头' },
          ],
        },
        component: <Input placeholder='请输入' disabled={actionType === 'update' || actionType === 'detail'} />,
      },
      {
        label: {
          label: '描述',
        },
        name: 'remark',
        options: {
          initialValue: remark,
          rules: [{ max: 256, message: '最长256个字符' }],
        },
        component: <Input.TextArea placeholder='请输入' />,
      },
    ].filter(Boolean);

    return (
      <CustomForm
        {...this.props}
        closeModal={this.props.closeModal}
        createForm={(ref) => (this.form = ref)}
        formItems={formItems}
        onHandleSubmit={this.handleSubmit}
        colNum={1}
        hideSubmit={this.actionType === 'detail'}
        modelId={null}
      />
    );
  }
}

export default TagAdd;
